package com.dgw.springbootstronger.aop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Logger;

/**
 * @program: springboot-stronger
 * @description:
 * @author: Mr.Dai
 * @create: 2020-03-01 14:57
 **/
@Component
public class ArithmeticCalculatorLoggingProxy {

    private final Logger logger=Logger.getLogger(ArithmeticCalculatorLoggingProxy.class.getName());

    @Autowired
    private Calculator calculator;

    public Calculator getProxy(){

        ClassLoader loader = calculator.getClass().getClassLoader();
        Class []  classes =new Class[]{Calculator.class};

        InvocationHandler invocationHandler = new InvocationHandler(){
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                Object o=null;
                try {
                    logger.info("前置通知:执行的方法名"+methodName);
                     o = method.invoke(calculator, args);
                    logger.info("返回通知:执行的方法名"+methodName);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                    logger.info("异常通知:执行的方法名"+methodName);
                }
                logger.info("后置通知:执行的方法名"+methodName);
                return o;
            }

        };
        return (Calculator) Proxy.newProxyInstance(loader,classes,invocationHandler);
    }
}
